// createContext用于做跨组件通信，类似于vue的依赖注入
import React, { Component, createContext } from "react";
import Child2 from "./Child2";

// 执行createContext会返回一个context对象
const context = createContext();
//     提供者(依赖) 消费者(注入)
export const { Provider, Consumer } = context;

// react的context的方式是有响应式的

class Child extends Component {
  render() {
    return (
      <>
        <div>
          child组件 -{" "}
          <Consumer>{(value) => <span>{value.name}</span>}</Consumer>
        </div>
        <Child2 />
      </>
    );
  }
}

class App extends Component {
  state = {
    name: "zhangsan",
    age: 20,
  };

  fn = () => {
    this.setState({
      name: "lisi",
    });
  };

  render() {
    return (
      // Provider组件必须要有一个value属性,value属性一般使用对象的形式
      <Provider
        value={{
          name: this.state.name,
          age: this.state.age,
        }}
      >
        <h2>
          context跨组件通信 - <button onClick={this.fn}>btn</button>
        </h2>
        <Child />
      </Provider>
    );
  }
}

export default App;
